package com.lazy.book.common.utils;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import com.lazy.book.common.constant.GlobalConstant;
import com.lazy.book.common.entity.LoginUser;

import java.util.Map;

public class LoginUtils {


  public static final String USER_KEY = "loginUser";

  private LoginUtils() {
    throw new IllegalStateException("Utility class");
  }

  public static void performLogin(LoginUser user, SaLoginParameter parameter, Map<String, Object> extraData) {
    parameter = ObjectUtil.defaultIfNull(parameter, SaLoginParameter.create());
    parameter.setExtraData(extraData);
    //登录生成token
    StpUtil.login(user.getUserInfo().getId(), parameter);
    StpUtil.getTokenSession().set(USER_KEY, user);
    //使用全局配置
    StpUtil.getTokenSession().updateTimeout(parameter.getTimeout());
    StpUtil.getSession().updateTimeout(parameter.getTimeout());
  }

  /**
   * 获取当前登录用户
   *
   * @return LoginUser
   */
  public static LoginUser getLoginUser() {
    SaSession session = StpUtil.getTokenSession();
    if (ObjectUtil.isNull(session)) {
      return null;
    }
    return (LoginUser) session.get(USER_KEY);
  }

  /**
   * 根据token获取用户信息
   *
   * @param token token
   * @return LoginUser
   */
  public static LoginUser getLoginUser(String token) {
    SaSession session = StpUtil.getTokenSessionByToken(token);
    if (ObjectUtil.isNull(session)) {
      return null;
    }
    return (LoginUser) session.get(USER_KEY);
  }

  public static boolean isSuperAdmin() {
    if (!StpUtil.isLogin()) {
      return false;
    }
    LoginUser loginUser = getLoginUser();
    if (loginUser == null) return false;
    return loginUser.getRoles().contains(GlobalConstant.SUPER_ROLE);
  }


}
